package com.linskating.wheat.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linskating.wheat.constant.RedisLockConstant;
import com.linskating.wheat.model.domain.User;
import com.linskating.wheat.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob implements RedisLockConstant {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private final List<Long> mainUsersList = List.of(1L);

    @Scheduled(cron = "0 56 15 * * *")
    public void doPreCacheRecommendUsers() {
        RLock lock = redissonClient.getLock(DO_PRE_CACHE_LOCK);
        try {
            // 看门狗机制，每隔10秒将过期时间重置为30秒
            if (lock.tryLock(0, -1, TimeUnit.SECONDS)) {
                ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
                for (Long userId : mainUsersList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 10), queryWrapper);
                    String redisKey = String.format("Wheat:user:recommend:%s", userId);
                    try {
                        stringObjectValueOperations.set(redisKey, userPage, 12, TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.error("Redis set key error!", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doPreCacheRecommendUsers error", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
